package com.koron.common.web.linkFile;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient;
import com.koron.bean.base.Attachment;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.common.service.AttachmentService;
import com.koron.common.core.config.ThreadLocalContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.List;

/**
 *  businessId      作为appId
 *  subBusinessId   作为版本号
 *  businessType    作为业务类型，ipa或apk
 */
@RestController
@RequestMapping(value = "linkFile")
@Api(tags = "外部链接文件")
@Slf4j
public class LinkFileController {

    private final String appId = "appBusinessIdV200";

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private DefaultFastFileStorageClient storageClient;

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    @ModelAttribute
    public void clearDbEnv(){
        getCurrUser().setCurrDs(null);
    }

    @ApiOperation("输电风控app上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "version", value = "版本号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "文件类型，ipa或apk", required = true, paramType = "query", dataType = "String")})
    @PostMapping("lineAppUpload")
    public Response<String> lineAppUpload(@RequestParam String version,
                                          @RequestParam(required = false, defaultValue = "apk")  String type,
                                          @RequestParam MultipartFile file) {
        attachmentService.uploadAttachmentWithTypeWithSubBusinessId(appId, version, type, file);
        return Response.ok();
    }

    @ApiOperation("获取输电风控app列表")
    @GetMapping("listLineAppInfo")
    public Response<List<Attachment>> listAppInfo(@RequestParam(required = false, defaultValue = "apk")  String type) {
        return Response.ok(attachmentService.getAttachmentListByBusinessIdWithType(appId, type));
    }

    @ApiOperation("获取最新的输电风控app")
    @GetMapping("latestLineAppInfo")
    public Response<Attachment> latestLineAppInfo(@RequestParam(required = false, defaultValue = "apk")  String type) {
        List<Attachment> attachmentList = attachmentService.getAttachmentListByBusinessIdWithType(appId, type);
        Attachment attachment = attachmentList.stream().max(Comparator.comparing(Attachment::getCreateTime)).orElse(null);
        return Response.ok(attachment);
    }

    @ApiOperation("下载输电风控app，不传版本则默认下载最新版")
    @GetMapping("downloadLineApp")
    public void downloadLineApp(@RequestParam(required = false) String version,
                                @RequestParam(required = false, defaultValue = "apk") String type,
                                HttpServletResponse response
                                ) throws UnsupportedEncodingException {
        Attachment attachment;
        if (StrUtil.isEmpty(version)) {
            List<Attachment> attachmentList = attachmentService.getAttachmentListByBusinessIdWithType(appId, type);
            attachment = attachmentList.stream().max(Comparator.comparing(Attachment::getCreateTime)).orElse(null);
        } else {
            List<Attachment> attachmentList = attachmentService.getAttachmentListByBusinessIdWithTypeWithSubBusinessId(appId, version, type);
            attachment = attachmentList.stream().max(Comparator.comparing(Attachment::getCreateTime)).orElse(null);
        }
        Assert.notNull(attachment, "该版本" + version + "的app不存在");
        StorePath storePath = StorePath.parseFromUrl(attachment.getPath());
        response.addHeader("size", attachment.getSize().toString());
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode(attachment.getName(), "UTF-8").replaceAll("\\+", "%20");
        if ("apk".equals(type)) {
            response.setContentType("application/vnd.android.package-archive;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        } else if ("ipa".equals(type)) {
            response.setContentType("application/vnd.iphone;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        }

        storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), inputStream -> {
            IoUtil.copy(inputStream, response.getOutputStream());
            IoUtil.close(inputStream);
            return null;
        });
        if (StrUtil.isEmpty(response.getHeader(HttpHeaders.CONTENT_LENGTH))) {
            response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(attachment.getSize()*1024));
        }
    }

}
